package web;

import common.consts.Consts;
import common.consts.Header;
import common.validation.ValidationResult;
import common.validation.Validators;
import org.apache.commons.lang3.StringUtils;
import web.security.JWT;
import web.security.JwtClaim;
import web.security.Protection;
import web.utils.IpUtil;
import web.utils.RequestHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by aceyin on 15/6/17.
 */
public class Request {
    private boolean protection;
    private int page;
    private int rows;

    public Request() {
        Protection prot = getClass().getAnnotation(Protection.class);
        if (prot != null) {
            this.protection = true;
        }
    }

    /**
     * Get the claims from Authorization header.
     *
     * @return
     */
    public JwtClaim getClaim() {
        String auth = request.getHeader(Header.AUTHORIZATION);
        if (StringUtils.isBlank(auth)) {
            return JwtClaim.EMPTY;
        }
        return JWT.getIdentity(auth);
    }

    private final HttpServletRequest request = RequestHolder.RAW_REQUEST.get();

    public HttpServletRequest raw() {
        return request;
    }

    public String ip() {
        return IpUtil.getClientIp(request);
    }

    public ValidationResult validate() {
        if (protection) {
            JwtClaim claim = getClaim();
            if (claim == JwtClaim.EMPTY) {
                return new ValidationResult(false, Consts.i18nKey.RESOURCE_NOT_ACCESSABLE);
            }
        }
        return Validators.validate(this);
    }

    public int getRows() {
        return rows <= 0 ? Consts.DEFAULT_ROWS : rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getPage() {
        return page <= 0 ? 1 : page;
    }

    public void setPage(int page) {
        this.page = page;
    }
}
